﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using GalaSoft.MvvmLight;
using SmartMusicBox.Model;
using Microsoft.Xna.Framework.Media;
using SmartMusicBox.ServiceModel;
using System.Windows.Threading;
using GalaSoft.MvvmLight.Command;
using System.Collections.Generic;
using SmartMusicBox.Logic;
using SmartMusicBox.Framework;
using SmartMusicBox.Framework.Helper;
using System.Diagnostics;

namespace SmartMusicBox.ViewModel
{
    public class PlayerViewModel : SmartViewModelBase
    {
        #region Property
        private Queue<SongPlayerModel> CurrentQueue;
        private bool StopByHand = false;
        private DispatcherTimer _tm = new DispatcherTimer();

        private SongPlayerModel _CurrentSong;
        public SongPlayerModel CurrentSong
        {
            get { return _CurrentSong; }
            set
            {
                _CurrentSong = value;
                this.RaisePropertyChanged("CurrentSong");
            }
        }

        private ButtonImageModel _ButtonResource;
        public ButtonImageModel ButtonResource
        {
            get { return _ButtonResource; }
            set
            {
                _ButtonResource = value;
                this.RaisePropertyChanged("ButtonResource");
            }
        }

        private RelayCommand _PlayCommand;

        public RelayCommand PlayCommand
        {
            get { return _PlayCommand; }
            set
            {
                _PlayCommand = value;
                this.RaisePropertyChanged("PlayCommand");
            }
        }

        private RelayCommand _FavCommand;

        public RelayCommand FavCommand
        {
            get { return _FavCommand; }
            set
            {
                _FavCommand = value;
                this.RaisePropertyChanged("FavCommand");
            }
        }

        private RelayCommand _NextCommand;
        public RelayCommand NextCommand
        {
            get { return _NextCommand; }
            set
            {
                _NextCommand = value;
                this.RaisePropertyChanged("NextCommand");
            }
        }
        #endregion

        #region Construct
        public PlayerViewModel()
        {
            Init();
        }
        #endregion

        #region Method

        void Init()
        {
            CurrentQueue = new Queue<SongPlayerModel>();
            BindButtonSource();
            BindCommand();
        }

        void BindButtonSource()
        {
            ButtonResource = new ButtonImageModel();
            ButtonResource.PlaySource = new System.Windows.Media.Imaging.BitmapImage(new Uri("/SmartMusicBox;component/Images/pause.png", UriKind.RelativeOrAbsolute));
            ButtonResource.FavSource = new System.Windows.Media.Imaging.BitmapImage(new Uri("/SmartMusicBox;component/Images/favourite.png", UriKind.RelativeOrAbsolute));
            ButtonResource.NextSource = new System.Windows.Media.Imaging.BitmapImage(new Uri("/SmartMusicBox;component/Images/next.png", UriKind.RelativeOrAbsolute));
        }

        void BindCommand()
        {
            MediaPlayer.MediaStateChanged += (o, e) =>
            {

                if (MediaPlayer.State == MediaState.Paused)
                {
                    if (!StopByHand)
                    {
                        Next();
                    }
                }
            };
            PlayCommand = new RelayCommand(() =>
            {
                if (MediaPlayer.State == MediaState.Stopped)
                {
                    Play();
                    StopByHand = false;
                    ChangeBtnImg("pause");
                }
                else if (MediaPlayer.State == MediaState.Paused)
                {
                    MediaPlayer.Resume();
                    StopByHand = false;
                    ChangeBtnImg("pause");
                }
                else
                {
                    MediaPlayer.Pause();
                    StopByHand = true;
                    ChangeBtnImg("play");
                }
            });

            NextCommand = new RelayCommand(() =>
            {
                Next();
            });

            FavCommand = new RelayCommand(() =>
            {
                ChangeBtnImg("like");
            });
        }
        
        void Play()
        {
            MediaPlayer.Stop();
            if (CurrentSong == null)
            {
                Next();
                return;
            }
            
            var s = Song.FromUri(CurrentSong.Title, new Uri(CurrentSong.URL));
            MediaPlayer.Play(s);

            _tm.Tick += new EventHandler((w, e) =>
            {
                if (MediaPlayer.State == MediaState.Playing)
                {
                    CurrentSong.PlayTime = string.Format("{0:00}:{1:00}", MediaPlayer.PlayPosition.Minutes, MediaPlayer.PlayPosition.Seconds);
                }
                else if (MediaPlayer.State == MediaState.Stopped)
                {
                    CurrentSong.PlayTime = string.Empty;
                    _tm.Stop();
                }
            });

            _tm.Interval = TimeSpan.FromSeconds(1);
            _tm.Start();
        }

        void Next()
        {
            if (CurrentQueue.Count == 0)
            {
                LoadNewSongListAndPlay();
            }
            else
            {
                CurrentSong = CurrentQueue.Dequeue();
                Play();
            }
        }

        void LoadNewSongListAndPlay()
        {
            SongLogic.SendRequestForGetSongs(CurrentSong.ChannelNo,
                   (songs) =>
                   {
                       DispatcherHelper.BeginInvokeOnUIThread(() =>
                       {
                           if (songs == null || songs.Length == 0)
                           {
                               Next();
                           }
                           else
                           {
                               foreach (var s in songs)
                               {
                                   CurrentQueue.Enqueue(new SongPlayerModel
                                   {
                                       ChannelNo = CurrentSong.ChannelNo,
                                       ChannelName = CurrentSong.ChannelName,
                                       Picture =SongLogic.GetImageSourceByUrl(s.Picture),
                                       Title = s.Title,
                                       URL = s.Url,
                                       SongInfo = SongLogic.GetSongInfo(s)
                                   });
                               }

                               CurrentSong = CurrentQueue.Dequeue();
                               Play();
                           }
                       });
                   },
                   (errmsg) =>
                   {
                       DispatcherHelper.BeginInvokeOnUIThread(() =>
                       {
                           Debug.WriteLine(errmsg);
                       });
                   });
        }

        public override void NavigateTo(object o)
        {
            if (o == null) return;

            var song = o as SongPlayerModel;
            if (CurrentSong == null || CurrentSong.ChannelName != song.ChannelName)
            {
                CurrentQueue.Clear();
                CurrentSong = song;
                Play();
            }
        }

        private void ChangeBtnImg(string type)
        {
            var url_play = "/SmartMusicBox;component/Images/play.png";
            var url_pause = "/SmartMusicBox;component/Images/pause.png";
            var url_fav = "/SmartMusicBox;component/Images/favourite.png";
            var url_like = "/SmartMusicBox;component/Images/like.png";
            
            if (type == "play")
            {
                ButtonResource.PlaySource = new System.Windows.Media.Imaging.BitmapImage (new Uri(url_play, UriKind.RelativeOrAbsolute));
            }
            else if (type == "pause")
            {
                ButtonResource.PlaySource = new System.Windows.Media.Imaging.BitmapImage(new Uri(url_pause, UriKind.RelativeOrAbsolute));
            }
            else if (type == "fav")
            {
                ButtonResource.FavSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(url_fav, UriKind.RelativeOrAbsolute));
            }
            else if (type == "like")
            {
                ButtonResource.FavSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(url_like, UriKind.RelativeOrAbsolute));
            }
        }
#endregion
    }
}
